#    GMail-Notifier - A cooler looking gmail notifier for Ubuntu
#    Copyright (C) 2009 Uday K Verma
#    Copyright (C) 2009 Ritesh Nadhani
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

# updatechecker.py
# check for updates on the predefined server location.
#

import urllib2
import gobject
import datetime

from gmailnotifier import __version__

class UpdateChecker(gobject.GObject):
    def __init__ (self):
        gobject.GObject.__init__(self)
        
        self.isUpdateNeeded = False
        self.lastUpdateCheckTime = None
        
    def isUpdateAvailable (self):
        self._checkForUpdates ()
        return self.isUpdateNeeded
        
    def getMenuItemDetails (self):
        return "Update Available: %s" % self._getDeployedVersionString (), "http://www.soundc.de/gmail-notifier"

    def _makeVersionNumber (self, str):
        parts = str.split ('.')
        while len(parts) < 3:
            parts.append ('0')
            
        return int(parts[0]) * 100 + int(parts[1]) * 10 + int(parts[2])
        
    def _getDeployedVersionString (self):
        try:
            f = urllib2.urlopen ('http://www.soundc.de/gmail-notifier/version')
            return f.read (1024).strip()  # our version string cannot be longer than this
        except:
            return None
    
    def _getPackageVersionString (self):
        return __version__
        
    def _getPackageVersionNumber (self):
        return self._makeVersionNumber (__version__)
        
    def _checkForUpdates (self):
        # not as often as we request, just once every hour
        this_time = datetime.datetime.now ()
        if not self.lastUpdateCheckTime or this_time - self.lastUpdateCheckTime > datetime.timedelta (seconds=3600):
            dep_ver = self._getDeployedVersionString ()
            if not dep_ver:
                self.isUpdateNeeded = False
            else:
                dep_ver_num = self._makeVersionNumber (dep_ver)
                cur_ver_num = self._getPackageVersionNumber ()
        
                self.isUpdateNeeded = dep_ver_num > cur_ver_num
            self.lastUpdateCheckTime = this_time
        

